const log4js      = require('../../data/log');
const logger      = log4js.getLogger('info');
const constants   = require('../../data/constants');
const alertModel  = require('../../model/alerts');
const basectrl    = require('./basectrl');
const fs          = require("fs");
/**
 * 报警信息
 */
let Alerts = {

    /**
     * 获取报警信息表
     * @param {*} req
     * @param {*} res
     * @returns
     */
    list:async function(req,res){
        if(!basectrl.hasLogin(req, res)){
            return;
        }
        let page = req.query.page;
        let pagesize = req.query.pagesize;

        let deviceid = req.query.deviceid;
        let channelid = req.query.channelid;

        if(typeof(page) == 'undefined') page=1;
        if(!pagesize) { pagesize=10000; }
        if(typeof(deviceid) == 'undefined') {
            deviceid=null;
            channelid=null;
        }

        let count = await alertModel.count(deviceid, channelid);
        alertModel.list(page-1, pagesize, deviceid, channelid).then((rows)=>{
            let ret =Object.assign(constants.httpCode.OK , {data: {items: rows, total: count, page: page, pagesize: pagesize}});
            res.send(ret);
        });
    },
    del:async function(req,res){
        if(!basectrl.hasLogin(req, res)){
            return;
        }
        let id = req.query.id;
        let model = await alertModel.get(id);
        logger.info('alert对象值', model);
        let picture = constants.cameraBak.savePath.PIC_ROOT + model.picture;
        logger.info('删除picture', picture);
        fs.unlink(picture, (err) => {
            if (err) throw err;
            console.log('文件已被删除');
        });
        let thumb = constants.cameraBak.savePath.PIC_ROOT+ model.thumb;
        logger.info('删除thumb', thumb);
        fs.unlink(thumb, (err) => {
            if (err) throw err;
            console.log('文件已被删除');
        });

        alertModel.del(id);
        res.send(Object.assign(constants.httpCode.OK, {data:null}));
    }
};
module.exports=Alerts;
